<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 缴费户号
 *
 * @icon fa fa-circle-o
 */
class Tickets extends Backend
{

    /**
     * Tickets模型对象
     * @var \app\admin\model\Tickets
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Tickets;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'])
                ->where($where)
                // ->group('order_no')
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname', 'mobile']);
            }

            $result = array(
                "total" => $list->total(),
                "rows" => $list->items(),
                // "chongfu" => \app\admin\model\Tickets::field('count(order_no) num,order_no')->group('order_no')->order('num desc')->limit('30')->select(),
                // "expire_at" => \app\admin\model\Bracelet::where([])->whereTime('expire_at', 'month')->count(),
                // "create_at" => \app\admin\model\Bracelet::where([])->whereTime('create_at', 'month')->count(),
                // "openid" => \app\admin\model\Tickets::where('openid', '<>', '')->count(),
                // "unionid" => \app\admin\model\Tickets::where('unionid', '<>', '')->count(),
                "unionid" => \app\admin\model\Tickets::where('unionid', '<>', '')->with(['user'])->where($where)->count(),
            );
            // $result['count'] = \app\admin\model\Bracelet::where(
            //     'address_id',
            //     'in',
            //     \app\admin\model\Tickets::where([])->column('address_id')
            // )->whereTime('expire_at', 'month')->count();
            // $id = 729408;
            // $address_id = Db::connect(\think\Config::get('db_b'))->name('store_member_address')->insertGetId([
            //     'member_id' => $id,
            //     'public_address_id' => 8888,
            //     'name' => $data['name'] ?? '测试',
            //     'phone' => $data['phone'] ?? 13888888888,
            //     'card_number' => $data['card_number'] ?? 8888,
            //     'province' => $data['province'] ?? '测试',
            //     'city' => $data['city'] ?? '测试',
            //     'area' => $data['area'] ?? '测试',
            //     'address' => $data['address'] ?? '测试',
            //     'num' => $data['num'] ?? 1,
            // ]);
            // Db::connect(\think\Config::get('db_b'))->name('store_member_address_log')->insert([
            //     'address_id' => $address_id,
            //     'price' => $data['price'] ?? 100,
            //     'num' => $data['num'] ?? 1,
            //     'order_no' => $order_no ?? time(),
            //     'payment_time' => date('Y-m-d H:i:s', $data['payment_time'] ?? time()),
            //     'pay_annual' => $data['pay_annual'] ?? '',
            //     'heating_way' => $data['heating_way'] ?? 1,
            // ]);
            // $result['create'] = \app\admin\model\Bracelet::create([
            //     'type' => 1,
            //     'mid' => $id,
            //     'price' => 100,
            //     'address_id' => 985005,
            //     'price_goods' => 200,
            //     'expire_at' => date('Y-m-d H:i:s', (time() + 60 * 60 * 24 * 31))
            //     // 'expire_at' => date('Y-m-d H:i:s', strtotime('+' . sysconf('coupon_expire') . ' days'))
            // ]);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function send($ids)
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $list = $this->model
                ->where('id', 'in', $ids)
                ->select();
            foreach ($list as $params) {
                $company = \app\admin\model\Company::where('name', $params['heating_company'])->find();
                if ($company && $company['appid'] && $company['secret']) {
                    $config = [
                        'app_id'    => $company['appid'] ?? '',
                        'secret'        => $company['secret'] ?? '',
                        'response_type' => 'array'
                    ];
                    $app = \EasyWeChat\Factory::officialAccount($config);
                    $new_params = [
                        'touser' => $params['openid'] ?? 'o8onm0jRa3oKKFFyM-UmEbU8OPLs',
                        'template_id' => $company['template_id'] ?: 'lwzP1ei696Ru7o5im04fPcpMjdHndg76cLLK_DDoDuc',
                        'appid' => $wxMiniProgram['app_id'] ?? 'wxd9486d8ee29b1ee9',
                        // 'url' => '',
                        // 'miniprogram' => [
                        //     'appid' => $wxMiniProgram['app_id'],
                        //     'pagepath' => 'pages/myCourse/myCourse',
                        // ],
                        'data' => [
                            'thing6' => ["value" => $params['name'] ?? '测试订单'],
                            'time5' => ["value" => date('Y-m-d H:i:s', time())],
                        ],
                    ];
                    $res = $app->template_message->send($new_params);
                    if ($res && !isset($res['errcode'])) {
                        $params->notice_time = time();
                        $params->save();
                    } else {
                        return $this->error('操作失败：' . $res['errmsg'], '', $res ?? []);
                    }
                    // var_dump($res);
                }
            }
            return $this->success('操作成功', '', $res ?? []);
        }
        return $this->view->fetch();
    }
}
